package com.dbq.share;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;

import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMusicObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXVideoObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;

import static com.dbq.share.YibaShareDelegateActivity.KEY_IS_TIMELINE;

/**
 * Created by sunkai on 2017/12/26.
 */

public class WxAssistActivity extends BaseAssistActivity {
    public static final String KEY_BROADCAST_ACTION = "wx_share_callback";
    public static final String KEY_BROADCAST_SHARE_SUCCESS = "wx_share_success";


    private boolean isTimeLine;

    private MyReceiver receiver;
    private IntentFilter filter;
    IWXAPI api;
    WXMediaMessage msg;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isTimeLine = getIntent().getExtras().getBoolean(KEY_IS_TIMELINE, false);
        receiver = new MyReceiver();
        filter = new IntentFilter();
        filter.addAction(KEY_BROADCAST_ACTION);
        api = WXAPIFactory.createWXAPI(getApplicationContext(), ShareUtil.WECHAT_APPID);
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(receiver, filter);
    }

    @Override
    protected void appNotInstallTips() {
        Toast.makeText(getApplicationContext(), R.string.dbq_socializ_wx_not_install, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected boolean appInstall() {
        return api.isWXAppInstalled();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(receiver);
    }

    @Override
    protected void sendMessage() {
        if (!isResume) {
            shareCancel();
            return;
        }
        startShare();
        switch (shareWebPage.ShareType) {
            case SocializeMediaConstant.PHOTO:
                WXImageObject imgObj = new WXImageObject(shareWebPage.thumb);
                msg = new WXMediaMessage(imgObj);
                break;
            case SocializeMediaConstant.MUSIC:
                WXMusicObject musicObj = new WXMusicObject();
                musicObj.musicUrl=shareWebPage.url;
                msg = new WXMediaMessage(musicObj);
                break;
            case SocializeMediaConstant.VIDEO:
                WXVideoObject videoObj = new WXVideoObject();
                videoObj.videoUrl = shareWebPage.url;
                msg = new WXMediaMessage(videoObj);
                break;
            case SocializeMediaConstant.TEXT:
                WXTextObject textObj = new WXTextObject();
                textObj.text = shareWebPage.description;
                msg = new WXMediaMessage(textObj);
                break;
            case SocializeMediaConstant.WEBLINK:
                WXWebpageObject webpageObject = new WXWebpageObject();
                webpageObject.webpageUrl = shareWebPage.url;
                msg = new WXMediaMessage(webpageObject);
                break;
        }
        msg.title = shareWebPage.title;
        msg.description = shareWebPage.description;
        msg.thumbData = bmpToByteArray(shareWebPage.thumb, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    public static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            boolean message = arg1.getBooleanExtra(KEY_BROADCAST_SHARE_SUCCESS, false);
            if (message) {
                shareSuccess();
            } else {
                shareCancel();
            }
            finish();
        }
    }

}
